<template>
  <div class="commentmanage-container" id="commentmanage-container" :class="scroll.isFixed ? 'maxHeight' : ''">
    <div class="ant-spin-container">
      <div
        :class="props.isSingle ? 'header-content single-header' : props.contentId ? 'header-content content-header' : 'header-content'">
        <slot></slot>
        <div class="header-right" v-if="props.tabKey === 1">
          <a-select class="header-select-area" v-model:value="selectInputValue" :options="selectInputOptions"
            @change="onSelectInput"></a-select>
          <a-input class="search-input" v-model:value="searchValue"
            :placeholder="`搜索${selectInputOptions[selectInputValue - 1].label}`" @keyup.enter.native="toSearchInput()">
            <template #suffix>
              <i @click="toSearchInput()" class="iconfont icon-search"></i>
            </template>
          </a-input>
          <a-button class="hight-select" @click="changeShowSelect">高级筛选</a-button>
        </div>
      </div>
      <div class="select-content" v-show="props.tabKey === 1 && isOpenSelectOption">
        <div class="select-item">
          <div class="title">审核状态：</div>
          <a-select v-model:value="auditStatus" :options="checkOptions" @change="onSelectType"></a-select>
        </div>
        <div class="select-item">
          <div class="title">回复状态：</div>
          <a-select v-model:value="replyStatus" :options="recoverOptions" @change="onSelectType"></a-select>
        </div>
        <div class="select-item" v-if="!props.contentId">
          <div class="title">选择栏目：</div>
          <a-tree-select class="AtreeSelect" placeholder="请选择" v-model:value="channelId" ref="usermanage_treeSelect"
            show-search :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }" allow-clear
            treeNodeFilterProp="channelName" :fieldNames="{ children: 'children', label: 'channelName', value: 'id' }"
            tree-default-expand-all :tree-data="props.upOrgOptions" @change="onSelectType">
          </a-tree-select>
        </div>
        <div class="select-item">
          <div class="title">评论时间：</div>
          <date-range-picker class="date-content" @change="changeTime" v-model:value="timeValue"
            :disabledInfo="{ type: 2, startDays: 0 }" :showTime="true" :valueFormat="valueFormat"></date-range-picker>
        </div>

        <div class="option-content">
          <a-button class="reset-btn" @click="resetOptions">重置</a-button>
          <div class="openorclose" @click="() => { isOpenSelectOption = false }" v-show="isOpenSelectOption">
            <a>收起</a>
            <i class="iconfont icon-up" style="font-size: 24px"> </i>
          </div>
        </div>
      </div>
      <a-empty style="margin-top: 200px;" v-if="isEmpty">
        <p style="color: #b6b6b6">暂无数据</p>
      </a-empty>
      <commentList :tabKey="props.tabKey" :isContent="props.contentId ? true : false"
        :isOpenSelectOption="isOpenSelectOption" :configData="configData" @toSingleMember="toSingleMember"
        @toSingleIp="toSingleIp" @checkPass="checkPass" @checkUnPass="checkUnPass" @forbidUserComment="forbidUserComment"
        @forbidIpComment="forbidIpComment" @changeReply="changeReply" @toDetele="toDetele" @toReply="toReply"
        @cancelReport="cancelReport" @deleteComment="deleteComment" @toAllComment="toAllComment"
        @checkedClick="checkedClick">
      </commentList>
      <pagination :pageSize="20" :dataSource="configData.records" @selectAll="selectAll" @changePage="changePage"
        :isSelect="true" :selfChecked="isSelectAll" :total="configData.total" :isShowPagination="isShowPagination"
        :simple="scroll.isFixed" :height="0" :showCheckDelete="showCheckDelete" :scroll="scroll" class="paginations"
        ref="tagBaseTables" v-if="configData.total > 0">
        <template #opration>
          <template v-if="props.tabKey === 1">
            <a-button :disabled="!selectList.length || !btnPerm.includes('auditPassAble')" @click="checkPassAll"
              :style="{ 'margin-left': '8px' }">审核通过</a-button>
            <a-button :disabled="!selectList.length || !btnPerm.includes('auditNoPassAble')" @click="checkUnPassAll"
              :style="{ 'margin-left': '8px' }">审核不通过</a-button>
            <a-button :disabled="!selectList.length || !btnPerm.includes('deleteAble')" @click="toDeteleAll" :style="{ 'margin-left': '8px' }">删除</a-button>
          </template>
          <template v-if="props.tabKey === 3">
            <a-button :disabled="!selectList.length || !btnPerm.includes('cancelReportAble')" @click="toCancelReport"
              :style="{ 'margin-left': '8px' }">取消举报</a-button>
            <a-button :disabled="!selectList.length || !btnPerm.includes('deleteCommentAble')" @click="toDeleteComment"
              :style="{ 'margin-left': '8px' }">删除评论</a-button>
          </template>
        </template>
      </pagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, createVNode, ref, watch } from "vue"
import commentList from './commentList.vue'
import { dataSourceType, scrollType, configDataType } from "@/type";
import request from "@/api/index";
import { Modal, message, TreeSelectProps } from "ant-design-vue";
import dateRangePicker from "@/components/picker/dateRangePicker.vue";
import { useRouter } from "vue-router";
import pagination from "@/components/pagination/index.vue";
import { getTableScroll } from "@/components/table/tableConfig/table";
import {routerPerm} from '@/utils/common';


//data
const btnPerm = ref<any[]>([]);
const router = useRouter();
const isOpenSelectOption = ref<boolean>(false);
const isEmpty = ref<boolean>(false);
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义
const valueFormat = ref("YYYY-MM-DD HH:mm:ss");
const isSelectAll = ref<boolean>(false);
const channelId = ref<any>('');

const searchValue = ref<string>('');
const commentator = ref<string>('');
const ipAddress = ref<string>('');
const comment = ref<string>('');
const replyContent = ref<string>('');
const title = ref<string>('');
const auditStatus = ref<any>(null);
const replyStatus = ref<any>(null);
const commentStartTime = ref<string>('');
const commentEndTime = ref<string>('');
const timeValue = ref<(string | number)[]>([]);
const checkOptions = [
  { label: "全部", value: null },
  { label: "待审核", value: 0 },
  { label: "审核通过", value: 1 },
  { label: "审核不通过", value: 2 },
];
const recoverOptions = [
  { label: "全部", value: null },
  { label: "未回复", value: 0 },
  { label: "已回复", value: 1 },
];


//props
const props = defineProps({
  isSingle: {
    type: Boolean,
    default: false,
  },
  ipAddress: {
    type: String,
    default: '',
  },
  commentator: {
    type: String,
    default: '',
  },
  contentId: {
    type: [Number, String,],
    default: '',
  },
  total: {
    type: Number,
    default: 0,
  },
  tabKey: {
    type: Number,
    default: 1,
  },
  upOrgOptions: {
    type: Array,
    default: [],
  },
});



const selectInputOptions = props.contentId ? [
  { label: "评论人", value: 1 },
  { label: "评论IP", value: 2 },
  { label: "评论内容", value: 3 },
  // { label: "回复内容", value: 4 },
  // { label: "文章标题", value: 5 },
] : (props.ipAddress ? [
  { label: "评论人", value: 1 },
  { label: "评论内容", value: 3 },
  // { label: "回复内容", value: 4 },
  { label: "文章标题", value: 4 },
] : (props.commentator ? [
  { label: "评论IP", value: 2 },
  { label: "评论内容", value: 3 },
  // { label: "回复内容", value: 4 },
  { label: "文章标题", value: 4 },
] : [
  { label: "评论人", value: 1 },
  { label: "评论IP", value: 2 },
  { label: "评论内容", value: 3 },
  // { label: "回复内容", value: 4 },
  { label: "文章标题", value: 4 },
]));
const selectInputValue = ref<number>(selectInputOptions[0].value);
let configData = reactive<configDataType>({ total: 0, size: 20, records: [] });
let scroll: scrollType = reactive({ y: "", isFixed: false });
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(20);
let rowSelection = ref<(string | number)[]>([]);
const selectList = ref<any[]>([]);

//emit
const emit = defineEmits(["updateReportCount"])

// 内容列表分页
const fetchCommentPage = async () => {
  let param = {
    auditStatus: auditStatus.value,
    channelId: channelId.value,
    contentId: props.contentId,
    comment: comment.value,
    commentStartTime: commentStartTime.value,
    commentEndTime: commentEndTime.value,
    commentator: commentator.value,
    ipAddress: ipAddress.value,
    pageNumber: pageCurrent.value,
    pageSize: pageSize.value,
    pageSort: '',
    replyContent: replyContent.value,
    replyStatus: replyStatus.value,
    singleIp: props.ipAddress,
    singleUser: props.commentator,
    title: title.value,
  }
  const data = await request.fetchCommentPage(param);
  configData.total = data.total;
  configData.records = data.records.map((item: dataSourceType) => {
    return Object.assign(item, { checked: false });
  });
  isEmpty.value = configData.total === 0 ? true : false
  nextTick(() => {
    let obj = getTableScroll(117, "commentmanage-container", 40);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};

const fetchCommentReportPage = async () => {
  let param = {
    pageNumber: pageCurrent.value,
    pageSize: pageSize.value,
    pageSort: '',
  }
  const data = await request.fetchCommentReportPage(param);
  configData.total = data.total;
  configData.records = data.records.map((item: dataSourceType) => {
    return Object.assign(item, { checked: false });
  });
  isEmpty.value = configData.total === 0 ? true : false
  nextTick(() => {
    let obj = getTableScroll(117, "commentmanage-container", 40);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};


// computed
rowSelection = computed(() => {
  return selectList.value;
});

//watch
watch(() => searchValue.value, (newVal: any, oldVal: any) => {
  if (selectInputValue.value === 1) {
    commentator.value = newVal
  } else if (selectInputValue.value === 2) {
    ipAddress.value = newVal
  } else if (selectInputValue.value === 3) {
    comment.value = newVal
  } else if (selectInputValue.value === 4) {
    title.value = newVal
  }
})

watch(() => props.tabKey, (newVal: any, oldVal: any) => {
  if (newVal === 1) {
    fetchCommentPage()
  } else if (newVal === 3) {
    fetchCommentReportPage()
  }
})

//method

//选择输入框
const onSelectInput = () => {
  searchValue.value = ''
  commentator.value = ''
  comment.value = '';
  replyContent.value = '';
  ipAddress.value = '';
  title.value = '';
}

//单个选择
const checkedClick = (item: any, index: number) => {
  selectList.value = [];
  configData.records[index].checked = !item.checked;
  nextTick(() => {
    isSelectAll.value = configData.records.every((item: any) => {
      return item.checked == true
    });

    configData.records.map((item: any) => {
      if (item.checked) {
        selectList.value.push(item.id);
      }
    });
  });
};
// 全选
const selectAll = () => {
  selectList.value = [];
  isSelectAll.value = !isSelectAll.value;
  configData.records.map((item: any) => {
    item.checked = isSelectAll.value;
    if (item.checked) {
      selectList.value.push(item.id);
    }
  });
};




//最上层输入框搜索
const toSearchInput = () => {
  fetchCommentPage()
}

//高级筛选
const onSelectType = () => {
  if (!channelId.value) {
    channelId.value = ''
  }
  fetchCommentPage()
}

// 筛选时间
const changeTime = (data: any) => {
  commentStartTime.value = data ? data[0] : null;
  commentEndTime.value = data ? data[1] : null;
  fetchCommentPage()
};

//打开高级筛选
const changeShowSelect = () => {
  isOpenSelectOption.value = !isOpenSelectOption.value
};


//重置
const resetOptions = () => {
  searchValue.value = '';
  auditStatus.value = null;
  replyStatus.value = null;
  channelId.value = null
  commentStartTime.value = '';
  commentEndTime.value = '';
  timeValue.value = []
  searchValue.value = '';
  comment.value = '';
  replyContent.value = '';
  ipAddress.value = '';
  title.value = '';
  commentator.value = ''
  fetchCommentPage()
};


//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  isSelectAll.value = false
  selectList.value = []
  props.tabKey === 1 ? fetchCommentPage() : fetchCommentReportPage()
};

//前往单个会员评论列表
const toSingleMember = (item: any) => {
  router.push({
    path: "/interaction/singleMember",
    // name: "单个会员评论",
    query: {
      commentator: item.commentator
    },
  });
}

//前往单个IP评论列表
const toSingleIp = (item: any) => {
  router.push({
    path: "/interaction/singleIp",
    // name: "单个会员评论",
    query: {
      ipAddress: item.ipAddress
    },
  });
}

//前往内容全部评论列表
const toAllComment = (item: any) => {
  router.push({
    path: "/interaction/allComment",
    query: {
      contentId: item.contentId,
      total: configData.total,
      channelName: item.channelName,
      title: item.title,
    },
  });
}

//批量通过
const checkPassAll = () => {
  Modal.confirm({
    content: "您确定将选中的评论审核通过？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      checkPass(selectList.value);
    },
    onCancel() { },
  });
}
//批量不通过
const checkUnPassAll = () => {
  Modal.confirm({
    content: "您确定将选中的评论审核不通过？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      checkUnPass(selectList.value);
    },
    onCancel() { },
  });
}

//批量删除
const toDeteleAll = () => {
  Modal.confirm({
    content: "您确定将选中的评论删除？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      toDetele(selectList.value);
    },
    onCancel() { },
  });
}
//批量取消举报
const toCancelReport = () => {
  Modal.confirm({
    content: "你是否确定批量取消举报？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      cancelReport(selectList.value);
    },
    onCancel() { },
  });
}
//批量删除评论
const toDeleteComment = () => {
  Modal.confirm({
    content: "你是否确定批量删除评论？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      deleteComment(selectList.value);
    },
    onCancel() { },
  });
}

//取消举报
const cancelReport = (ids: any[]) => {
  request
    .fetchCommentCancelReport({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentReportPage();
        emit('updateReportCount')
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}
//删除评论
const deleteComment = (ids: any[]) => {
  request
    .fetchCommentDelete({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentReportPage();
        emit('updateReportCount')
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}
//审核通过
const checkPass = (ids: any[]) => {
  request
    .fetchCommentAuditPass({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

//审核不通过
const checkUnPass = (ids: any[]) => {
  request
    .fetchCommentAuditFailed({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

//禁止用户评论
const forbidUserComment = (item: any) => {
  request[item.isUserSilenced ? 'commentCancelSilencedCommentator' : 'fetchCommentSilencedCommentator']({ id: item.id })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

//禁止IP评论
const forbidIpComment = (item: any) => {
  request[item.isIpSilenced ? 'commentCancelSilencedCommentIp' : 'fetchCommentSilencedCommentIp']({ id: item.id })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

//新增回复
const toReply = (comment: string, id: number) => {
  request
    .fetchCommentAdminReply({ comment, commentId: id })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        message.success('回复成功');
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

//修改回复
const changeReply = (comment: string, id: number) => {
  request
    .fetchCommentUpdateAdminReply({ comment, id })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        message.success('修改回复成功');
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}

//删除
const toDetele = (ids: any[]) => {
  request
    .fetchCommentDelete({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        fetchCommentPage();
        selectList.value = [];
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
}


//onMounted
onMounted(() => {
  btnPerm.value = routerPerm();
  props.tabKey === 1 ? fetchCommentPage() : fetchCommentReportPage()
})
</script>

<style lang="less" scoped>
.maxHeight {
  max-height: calc(100% - 120px) !important;
}

.commentmanage-container {
  height: calc(100% - 120px);
  background-color: #fff;
  border-radius: 2px;
  padding: 16px;

  .header-content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);

    ::v-deep(.ant-tabs-tab) {
      padding: 8px 0;
    }

    ::v-deep(.ant-tabs-top > .ant-tabs-nav::before, .ant-tabs-bottom > .ant-tabs-nav::before, .ant-tabs-top > div > .ant-tabs-nav::before, .ant-tabs-bottom > div > .ant-tabs-nav::before) {
      border: none
    }

    .header-right {
      display: flex;
      flex-direction: row;

      .header-select-area {
        width: 104px;
        height: 32px;
      }

      .search-input {
        width: 192px;
        margin-left: 12px;
        border-radius: 2px;
        height: 32px;

        .icon-search {
          font-size: 20px;
          line-height: 20px;
          color: rgba(0, 0, 0, 0.45);
        }
      }

      .hight-select {
        margin-left: 8px;
      }
    }
  }

  .single-header {
    justify-content: end;
    border: none;
    background: #fff;
  }

  .content-header {
    border: none;
    background: #fff;
  }


}

.select-content {
  background: rgba(0, 0, 0, 0.02);
  display: flex;
  margin-top: 16px;
  padding: 16px;
  flex-wrap: wrap;


  .select-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 16px;

    .title {
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      width: 70px;
    }

    .ant-select {
      flex: 1;
    }

    .ant-picker-range {
      flex: 1;
    }

    .titleSelect {
      width: 100px;
      margin-right: 12px;
    }
  }


  .option-content {
    flex: 1;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    height: 32px;
    margin-top: 16px;

    .reset-btn {
      height: 32px;
    }

    .openorclose {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-left: 16px;
      font-size: 14px;
      line-height: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #1f6ded;

      .iconfont {
        margin-left: 4px;
      }
    }
  }
}
</style>
<style>
@media screen and (max-width: 1600px) and (min-width:1280px) {
  .select-content .select-item {
    width: calc(50% - 8px);
  }

  .select-content .select-item:nth-of-type(2n-1) {
    margin-right: 16px;
  }
}

@media screen and (max-width: 1920px) and (min-width: 1601px) {
  .select-content .select-item {
    width: calc(32.99% - 8px);
    ;
  }

  .select-content .select-item:nth-of-type(1) {
    margin-right: 16px;
  }

  .select-content .select-item:nth-of-type(2) {
    margin-right: 16px;
  }
}

@media screen and (max-width: 2560px) and (min-width: 1921px) {
  .select-content .select-item {
    width: calc(25% - 8px);
  }

  .select-content .select-item {
    margin-right: 16px;
  }

  .select-content .select-item:nth-of-type(4) {
    margin-right: 0px;
  }
}
</style>